<?php


namespace app\plugin\controller\article;


use app\common\controller\AppCommon;
use app\plugin\controller\article\com\ArticleManager;
use app\plugin\controller\article\service\ArticleService;
use app\service\DiyLog;
use app\service\Page;

class Manager extends ArticleManager
{
    public function index()
    {
        ArticleService::ini_sql();
        $where = [];
        $page = !empty($this->param['page']) ? intval($this->param['page']) : 1;
        $pageSize = 10;

        $status = isset($this->param['status']) && is_numeric($this->param['status']) ? intval($this->param['status']) : '';
        $keyword = !empty($this->param['keyword']) ? trim($this->param['keyword']) : '';
        $orderBy = 'id desc';


        if ($status !== '') {
            $where['status'] = $status;
        }

        if (!empty($keyword)) {
            $where['title'] = ['like', '%' . $keyword . '%'];
        }


        $status = [
            '1' => '<span class="bs-green">上架中</span>',
            '0' => '<span class="bs-red">已下架</span>',
        ];
        $data = AppCommon::data_list('plugin_article', $where, $page . ',' . $pageSize, 'title,id,status,count_view,add_time,up_time,price,aid,sale_count', $orderBy);

        if (!empty($data)) {

            array_walk($data, function (&$v, $k, $arg) {
                $v['up_time'] = date('Y-m-d H:i:s', $v['up_time']);
                $v['add_time'] = date('Y-m-d H:i:s', $v['add_time']);
                $v['statusDesc'] = $arg['status'][$v['status']];
            }, ['status' => $status]);
        }

        $total = AppCommon::data_count('plugin_article', $where);

        $this->assign('page', Page::set($data, $pageSize, $page, $total, $this->param, url()));
        $this->assign('data', $data);
        return $this->fetch();
    }

    public function article_form()
    {
        $id = !empty($this->param['id']) ? intval($this->param['id']) : 0;
        if (!empty($id)) {
            $data = AppCommon::data_get('plugin_article', ['id' => $id]);
            if (!empty($data)) {
                $this->assign('data', $data);
            }

        }

        $this->assign('category', $this->category(true));
        return $this->fetch();
    }

    public function article_action()
    {
        $id = !empty($this->param['id']) ? intval($this->param['id']) : 0;
        $ac = !empty($this->param['ac']) ? trim($this->param['ac']) : '';
        if (!empty($id)) {
            $data = AppCommon::data_get('plugin_article', ['id' => $id]);
            if (empty($data)) {
                data_return('记录不存在', -1);
            }
            //仅删除
            if ($ac == 'del') {
                if ($data['sale_count'] > 0) {
                    data_return('已被购买过的不支持删除', -1);
                }
                AppCommon::data_del('plugin_article', ['id' => $data['id']]);
                data_return('删除成功');
            }
        }
        if ($ac == 'status') {
            AppCommon::data_update('plugin_article', ['id' => $data['id']], [
                'up_time' => time(),
                'status' => $data['status'] == 1 ? 0 : 1
            ]);
            data_return('状态已修改');
        }elseif ($ac=='copy'){
            $aid = get_random(10);
            while (true) {
                $has = AppCommon::data_get('plugin_article', ['aid' => $aid], 'id');
                if (empty($has)) {
                    break;
                }
                $aid = get_random(10);
            }

            AppCommon::data_add('plugin_article', [
                'title' => $data['title'].'_copy',
                'desc' => $data['desc'],
                'content' => $data['content'],
                'author' => $data['author'],
                'category_id' => intval($data['category_id']),
                'price' => floatval($data['price']),
                'up_time' => time(),
                'add_time' => time(),
                'aid' => $aid,
                'status' => 0,
            ]);
            data_return('复制成功');
        }
        if (empty($this->param['title'])) {
            data_return('请填写标题', -1);
        }
        if (empty($this->param['content'])) {
            data_return('请填写内容', -1);
        }

        if (empty($this->param['desc'])) {
            $this->param['desc'] = mb_strcut(strip_tags(htmlspecialchars_decode($this->param['content'])),0,500,'utf-8').'......';
        }else{
            $this->param['desc'] = strip_tags(htmlspecialchars_decode($this->param['desc']));
        }

        /*if ($this->param['free_percent'] < 0 || $this->param['free_percent'] > 100) {
            data_return('试读比例在0~100', -1);
        }*/
        if (!empty($data)) {
            AppCommon::data_update('plugin_article', ['id' => $data['id']], [
                'title' => trim($this->param['title']),
                'desc' => $this->param['desc'],
                'content' => $this->param['content'],
                'author' => $this->param['author'],
                'category_id' => intval($this->param['category_id']),
               // 'free_percent' => intval($this->param['free_percent']),
                'price' => floatval($this->param['price']),
                'up_time' => time(),
                'status' => !empty($this->param['status']) ? 1 : 0,
            ]);
        } else {
            $aid = get_random(10);
            while (true) {
                $has = AppCommon::data_get('plugin_article', ['aid' => $aid], 'id');
                if (empty($has)) {
                    break;
                }
                $aid = get_random(10);
            }

            AppCommon::data_add('plugin_article', [
                'title' => trim($this->param['title']),
                'desc' => $this->param['desc'],
                'content' => $this->param['content'],
                'author' => $this->param['author'],
                'category_id' => intval($this->param['category_id']),
               // 'free_percent' => intval($this->param['free_percent']),
                'price' => floatval($this->param['price']),
                'up_time' => time(),
                'add_time' => time(),
                'aid' => $aid,
                'status' => !empty($this->param['status']) ? 1 : 0,
            ]);
        }

        data_return('操作成功');
    }

    function category($getData = false)
    {
        $data = AppCommon::data_list_nopage('plugin_article_category', [], '*', 'id desc');
        if ($getData) {
            return tree($data, 'id', 'fid', 'subcat');
        }
        if ($data) {
            $this->assign('data', tree($data, 'id', 'fid', 'subcat'));
        }
        return $this->fetch();
    }

    public function category_form()
    {
        if (!empty($this->param['id'])) {
            $this->assign('data', AppCommon::data_get('plugin_article_category', ['id' => intval($this->param['id'])]));
        }
        $this->assign('category', $this->category(true));
        return $this->fetch();
    }


    public function category_action()
    {
        $id = !empty($this->param['id']) ? intval($this->param['id']) : 0;
        if (!empty($id)) {
            $data = AppCommon::data_get('plugin_article_category', ['id' => $id]);
            if (empty($data)) {
                data_return('数据不存在', -1);
            }
            //仅删除
            if (!empty($this->param['ac']) && $this->param['ac'] == 'del') {
                $res = AppCommon::data_del('plugin_article_category', ['id' => $data['id']]);

                $ids = [$data['id']];
                if ($res) {
                    $two = AppCommon::data_list_nopage('plugin_article_category', ['fid' => $data['id']], 'id');
                    if (!empty($two)) {
                        $ids = array_merge($ids, array_column((array)$two, 'id'));
                        //移除二级
                        $ret = AppCommon::data_del('plugin_article_category', ['fid' => $data['id']]);

                        if ($ret) {
                            //移除三级
                            AppCommon::data_del('plugin_article_category', ['fid' => ['in', array_column((array)$two, 'id')]]);
                            //所有三级
                            $three = AppCommon::data_list_nopage('plugin_article_category', ['id' => ['in', array_column((array)$two, 'id')]], 'id');
                            $ids = array_merge($ids, array_column((array)$three, 'id'));
                        }
                    }
                }
                if (!empty($ids)) {
                    AppCommon::data_update('plugin_article', ['category_id' => ['in', $ids]], ['category_id' => 0]);
                }

                data_return('删除成功');
            }
        }
        if (empty($this->param['title'])) {
            data_return('分类名称未设置', -1);
        }


        $baseData = [
            'name' => trim($this->param['title']),
            'fid' => intval($this->param['fid']),
            'status' => !empty($this->param['status']) ? 1 : 0,
        ];
        if (empty($data) && AppCommon::data_get('plugin_article_category', ['fid' => $baseData['fid'], 'name' => $baseData['name']], 'id')) {
            data_return('分类已存在', -1);
        }
        if (!empty($data)) {
            AppCommon::data_update('plugin_article_category', ['id' => $data['id']], $baseData);
        } else {
            AppCommon::data_add('plugin_article_category', $baseData);
        }
        data_return('操作成功');
    }

    public function urls()
    {
        $data = [
            ['name'=>'首页','url'=>URL_WEB.trim(url('/plugin/article.client/index'),'/')],
            ['name'=>'已购列表','url'=>URL_WEB.trim(url('/plugin/article.client/index',['from'=>'buy']),'/')],
        ];
        $this->assign('data',$data);
        return $this->fetch();
    }

    public function setting()
    {
        return $this->error('暂无需配置');
    }
}